package com.example.docking.controller;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.request.CommonOperateDao;
import com.example.docking.dao.jindie.request.MoTaskBillRequest;
import com.example.docking.dao.jindie.response.*;
import com.example.docking.dao.jindie.response.motaskbill.SubMaterialEntity;
import com.example.docking.dao.jingxin.request.ApplyOrderSum;
import com.example.docking.dao.jingxin.request.ApplyOrderWcqd;
import com.example.docking.dao.jingxin.request.ApplyOrderWgqd;
import com.example.docking.dao.jingxin.request.ApplyOrderWxqd;
import com.example.docking.service.impl.DataServiceImpl;
import com.example.docking.service.impl.MoTaskbillServiceImpl;
import com.example.docking.service.impl.PurRequestServiceImpl;
import com.example.docking.util.Constants;
import com.example.docking.util.TimeRangeMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName PurRequestController
 * @Description 需求：
 * 获取进行的采购申请单数据
 * @Author zhanghuiping
 * @Date 2025 - 05 - 06 02:32:41
 */


@RestController
@RequestMapping("/PurRequest")
@EnableAsync
public class PurRequestController {
    private static final Logger logger = LoggerFactory.getLogger(PurRequestController.class);

    @PostMapping("/save")
    public String InsertPurRequest(@Valid @RequestBody String applyOrderSum) {
        MDC.put("requestId", UUID.randomUUID().toString());
        logger.info("数据进来了");
        logger.info("applyOrderSum: {}", applyOrderSum);
        logger.info("数据信息");

        Gson gson = new Gson();
        ApplyOrderSum applyOrderSum1 = gson.fromJson(applyOrderSum, ApplyOrderSum.class);
        ResponseData responseDataresult = new ResponseData();
        if (applyOrderSum1 != null) {
            logger.info("敬信传送过来采购申请单数据：" + applyOrderSum1.getOrderCode());
            String emp = "zhansan";
            String task_no = applyOrderSum1.getOrderCode();
            List<ApplyOrderWcqd> listWcqd = applyOrderSum1.getWcList();
            List<ApplyOrderWgqd> listWgqd = applyOrderSum1.getWgList();
            List<ApplyOrderWxqd> listWxqd = applyOrderSum1.getWxList();
            PurRequestServiceImpl purRequestService = new PurRequestServiceImpl();
            List<SubMaterialEntity> subMaterialEntityList = new ArrayList<>();
            int i = 1;
            if (listWcqd != null && listWcqd.size() > 0) {
                //查询当天未审核的，备注里面有没有已经存的，有返回id 值，修改，没有新增
                String idcode = SelectPurRequestOrder(task_no, "外采");
                logger.info("id: {}", idcode);
                logger.info("进入外采数据处理");
                responseDataresult = purRequestService.InsertPurRequestWcqd(emp, task_no, listWcqd, subMaterialEntityList, idcode);
                if (responseDataresult.getErrcode() != 0) {
                    logger.info("进入外采数据处理失败");
                    logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                    return gson.toJson(responseDataresult);
                }

            }

            if (listWgqd != null && listWgqd.size() > 0) {
                String idcode = SelectPurRequestOrder(task_no, "外购");
                logger.info("id: {}", idcode);
                logger.info("进入外购数据处理");
                responseDataresult = purRequestService.InsertPurRequestWgqd(emp, task_no, listWgqd, subMaterialEntityList, idcode);
                if (responseDataresult.getErrcode() != 0) {
                    logger.info("进入外购数据处理失败");
                    logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                    return gson.toJson(responseDataresult);
                }

            }

            if (listWxqd != null && listWxqd.size() > 0) {
                String idcode = SelectPurRequestOrder(task_no, "外协");
                logger.info("id: {}", idcode);
                logger.info("进入外协数据处理");
                responseDataresult = purRequestService.InsertPurRequestWxqd(emp, task_no, listWxqd, subMaterialEntityList, idcode);
                if (responseDataresult.getErrcode() != 0) {
                    logger.info("进入外协数据处理失败");
                    logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                    return gson.toJson(responseDataresult);
                }

            }
            logger.info("低阶材料个数：" + subMaterialEntityList.size());
            MoTaskbillServiceImpl MotaskService = new MoTaskbillServiceImpl();
            MoTaskbillData moTaskbillData = MotaskService.getMoTaskbillDataByBillno(task_no);
            if (moTaskbillData != null) {
                logger.info("进入生产工单数据处理");
                MoTaskBillRequest moTaskBillRequest = new MoTaskBillRequest();
                String id = moTaskbillData.getId();
                logger.info("生产工单id:" + id);
                moTaskBillRequest.setId(id);
                //反审核
                logger.info("开始反审核");
                responseDataresult = unauditTaskOrder(id);
                if (responseDataresult.getErrcode() != 0) {
                    logger.info("反审核失败");
                    logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                    return gson.toJson(responseDataresult);
                }
                logger.info("反审核成功");
                //获取订单详情
                MoTaskbillDetailData moTaskbillDetailData = MotaskService.getMoTaskbillDetaillByBillno(id);
                if (moTaskbillDetailData != null) {
                    logger.info("修改工单数据");
                    List<MaterialEntity> materialEntities = moTaskbillDetailData.getMaterial_entity();
                    MaterialEntity materialEntitynew = new MaterialEntity();
                    MaterialEntity materialEntity = materialEntities.get(0);
                    materialEntitynew.setId(materialEntity.getId());
                    materialEntitynew.setSub_material_entity(subMaterialEntityList);
                    List<MaterialEntity> materialEntities1 = new ArrayList<>();
                    materialEntities1.add(materialEntitynew);
                    moTaskBillRequest.setMaterial_entity(materialEntities1);
                    //修改生产任务单
                    responseDataresult = MotaskService.insertBYTran(moTaskBillRequest);
                    if (responseDataresult.getErrcode() != 0) {
                        logger.info("修改工单失败");
                        logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                        return gson.toJson(responseDataresult);
                    }
                    logger.info("修改工单成功");
                }
                //审核
                logger.info("二次审核开始");
                responseDataresult = auditTaskOrder(moTaskbillData.getId());
                if (responseDataresult.getErrcode() != 0) {
                    logger.info("二次审核失败");
                    logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
                    return gson.toJson(responseDataresult);
                }
                logger.info("二次审核成功");
            } else {
                logger.info("未查询到生产工单信息，修改失败");
                responseDataresult.setErrcode(10009);
                responseDataresult.setDescription("没有查询到生产任务信息");
                return gson.toJson(responseDataresult);
            }
            logger.info("数据流程走完了");
            logger.info("处理前:" + gson.toJson(responseDataresult));
        } else {
            responseDataresult.setErrcode(100008);
            responseDataresult.setDescription("JSON 转换失败");
        }
        ResponseData responseDataresult1 = new ResponseData();
        responseDataresult1.setErrcode(responseDataresult.getErrcode());
        responseDataresult1.setDescription(responseDataresult.getDescription());
        responseDataresult1.setData(responseDataresult.getData());
        if (responseDataresult.getErrcode() == 0) {
            responseDataresult.setErrcode(0);
            responseDataresult.setDescription("success");
            responseDataresult.setData(null);
            logger.info("json==" + gson.toJson(responseDataresult1));
            logger.info("json==" + gson.toJson(responseDataresult));
            return gson.toJson(responseDataresult1);
        }
        logger.info("处理后：responseDataresult1:" + responseDataresult1);
        logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult.getErrcode() + "描述" + responseDataresult.getDescription());
        logger.info("PurRequestController-调用采购申请单数据返回：" + responseDataresult1.getErrcode() + "描述" + responseDataresult1.getDescription());

        logger.info("json==" + gson.toJson(responseDataresult1));
        MDC.clear();
        return gson.toJson(responseDataresult1);
    }

    private static ResponseData unauditTaskOrder(String id) {
        ResponseData responseData = new ResponseData();
        if (id == null || id.equals("")) {
            responseData.setErrcode(100002);
            responseData.setDescription("审核id为空");
            return responseData;
        }
        DataServiceImpl dataService = new DataServiceImpl();
        Gson gson = new Gson();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        HashMap<String, String> map = new HashMap<>();
        logger.info("反审核：生产任务单ids: {}", ids);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.MO_TASK_BILL_TYPE);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.UNAUDIT);
        ResponseData<SaveData> response = null;
        try {
            ApiResult auditData = dataService.SelectDataAudit(Constants.COMMON_OPERATE, map, commonOperateDao);
            Type type1 = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            response = gson.fromJson(auditData.getBody(), type1);
            if (response.getErrcode() == 0) {
                logger.info("反审核：审核生产任务成功");
                logger.info("反审核：审核生产任务单Code: {}", response.getErrcode());
                logger.info("反审核：审核生产任务单Message: {}", response.getDescription());
                logger.info("反审核：审核生产任务单data: {}", response.getData());
            } else {
                logger.error("反审核：审核生产任务单失败. Errcode: {}, Description: {}", response.getErrcode(), response.getDescription());
            }
        } catch (Exception e) {
            logger.error("反审核：Error occurred while auditing sales order", e);
        }
        responseData = response;
        logger.info("反审核返回：responseData=" + responseData);
        return responseData;
    }

    private static ResponseData auditTaskOrder(String id) {
        ResponseData responseData = new ResponseData();
        if (id == null || id.equals("")) {
            responseData.setErrcode(100002);
            responseData.setDescription("审核id为空");
            return responseData;
        }
        DataServiceImpl dataService = new DataServiceImpl();
        Gson gson = new Gson();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        HashMap<String, String> map = new HashMap<>();
        logger.info("二次审核：生产任务单ids: {}", ids);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.MO_TASK_BILL_TYPE);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.AUDIT);
        ResponseData<SaveData> response = null;
        try {
            ApiResult auditData = dataService.SelectDataAudit(Constants.COMMON_OPERATE, map, commonOperateDao);
            Type type1 = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            response = gson.fromJson(auditData.getBody(), type1);
            if (response.getErrcode() == 0) {
                logger.info("二次审核：审核生产任务成功");
                logger.info("二次审核：审核生产任务单Code: {}", response.getErrcode());
                logger.info("二次审核：审核生产任务单Message: {}", response.getDescription());
                logger.info("二次审核：审核生产任务单data: {}", response.getData());
            } else {
                logger.error("二次审核：审核生产任务单失败. Errcode: {}, Description: {}", response.getErrcode(), response.getDescription());
            }
        } catch (Exception e) {
            logger.error("二次审核：Error occurred while auditing sales order", e);
        }
        responseData = response;
        logger.info("二次审核返回：responseData=" + responseData);
        return responseData;
    }

    public String SelectPurRequestOrder(String taskno, String supplier) {
        String id = null;
        logger.info("查询采购申请单id:" + taskno);
        Gson gson = new Gson();
        int page = 1; // 初始页码
        int pageSize = 20; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        map.put("bill_status", "Z");//单据状态（所有：“”，已审核：“C”，未审核：“Z”）
        //创建时间-结束时间的时间戳(毫秒)
        TimeRangeMap timeRangeMap = new TimeRangeMap();
        map.put("modify_start_time", timeRangeMap.getDayStartTime()); //    创建时间-开始时间的时间戳(毫秒)
        map.put("modify_end_time", timeRangeMap.getDayEndTime()); //  	创建时间-结束时间的时间戳(毫秒)
        DataServiceImpl Service = new DataServiceImpl();
        ApiResult result1 = null;
        ApiResult result2 = null;
        try {
            result1 = Service.SelectDataList(Constants.PUR_REQUEST, map, "");
            Type type1 = new TypeToken<ResponseData<GenericDataItem<PurRequestData>>>() {
            }.getType();
            ResponseData<GenericDataItem<PurRequestData>> response1 = gson.fromJson(result1.getBody(), type1);
            GenericDataItem<PurRequestData> orderListGenericDataItem = response1.getData();
            List<PurRequestData> PurRequestlist = orderListGenericDataItem.getRows();
            for (PurRequestData purRequestlist1 : PurRequestlist) {
                String billid = purRequestlist1.getId();
                HashMap<String, String> map1 = new HashMap<>();
                String sup = purRequestlist1.getWhole_supplier_name();
                //区分外采 外购 外协
                if (supplier.equals(sup)) {
                    map1.put("page", String.valueOf(page));
                    map1.put("page_size", String.valueOf(pageSize));
                    map1.put("id", billid);
                    result2 = Service.SelectDataDetail(Constants.PUR_REQUEST_DETAIL, map1, "");
                    Type type2 = new TypeToken<ResponseData<PurRequestDetailData>>() {
                    }.getType();
                    ResponseData<PurRequestDetailData> response2 = gson.fromJson(result2.getBody(), type2);
                    PurRequestDetailData purRequestDetailData = response2.getData();
                    String remark = purRequestDetailData.getRemark();
                    if (remark == null || remark.equals("")) {
                        continue;
                    }
                    logger.info("remark: {}", remark);
                    logger.info("taskno: {}", taskno);
                    if (remark.equals(taskno)) {
                        id = purRequestlist1.getId();
                        break;

                    }
                }
            }
        } catch (Exception e) {
            logger.error("查询采购申请单id发生异常", e);
            throw new RuntimeException(e);
        }
        return id;
    }

    public static void main(String[] args) {
        PurRequestController purRequestController = new PurRequestController();
        String id = purRequestController.SelectPurRequestOrder("SCRW-20250427-00001", "");
        System.out.println(id);
    }
}